//
//  OAuthViewController.swift
//  SinaWeiBo20
//
//  Created by tarena on 16/3/20.
//  Copyright © 2016年 tarena. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD


//AppKey:2910864654
//AppSecret:59525787553688e5503cc26132b5030d
//uri:http://open.weibo.com/

class OAuthViewController: UIViewController {

    //定义一个webView属性
    let webView = UIWebView()
    
    //监听方法
    @objc private func goBackClick() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    
    @objc private func fullAccount() {
        let jsString = "document.getElementById('userId').value = '18257102706';"
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        
        
    }
    
    
    private func setupUI() {
        view = webView
        webView.delegate = self
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: .Plain, target: self, action: "goBackClick")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "上次登录", style: .Plain, target: self, action: "fullAccount")
        loadOauthPage()
    }
   
    
    private func loadOauthPage(){
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + appid + "&" + "redirect_uri=" + redirect_uri
        webView.loadRequest(NSURLRequest(URL: NSURL(string: urlString)!))
       
    }
    
    override func viewDidDisappear(animated: Bool) {
        SVProgressHUD.dismiss()
    }
    
    

}


//专门处理 webView所用的协议方法
extension OAuthViewController: UIWebViewDelegate {
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        SVProgressHUD .showErrorWithStatus("网页加载失败")
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
//       print(request.URL?.absoluteString)
        let urlString:String = (request.URL?.absoluteString)!
        if urlString.containsString("code=") {
            let range:Range = urlString.rangeOfString("code=")!
            let code :String = urlString.substringFromIndex(range.last!.advancedBy(1))
            UserAccountViewModel().OAuthAccessToken(code, finished: { (error) -> () in
                if (error != nil) {
                    SVProgressHUD.showInfoWithStatus("网络君正在睡觉,请稍后再来")
                    return
                }
                //modal出来的页面 被dismiss 掉 不会立即被回收
                self.dismissViewControllerAnimated(true, completion: { () -> Void in
                    //发出页面切换的通知
                    NSNotificationCenter.defaultCenter().postNotificationName(AppSwitchRootViewController, object: "Welcome")
                    print("come here")
                    
                })
                
            })
        }
        return true
    }
    
    
    
    

}
